package com.ica.android.ui.policy;

import java.util.List;
import java.util.Vector;

import com.ica.R;
import com.ica.model.facade.PolicyFacadeMockImpl;
import com.ica.model.facade.PolicyFacadeInterface;
import com.ica.model.policy.Policy;

import android.app.AlertDialog;
import android.app.ListActivity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.telephony.TelephonyManager;
import android.view.ContextMenu;
import android.view.ContextMenu.ContextMenuInfo;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.AdapterContextMenuInfo;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.Toast;

/**
 * @author             Hector
 * @uml.dependency   supplier="com.ica.android.ui.policy.PolicyActivity"
 */
public class PolicyManagementActivity extends ListActivity {
	
	/**
	 * @uml.property  name="policyFacade"
	 * @uml.associationEnd  
	 */
	private PolicyFacadeMockImpl policyFacade = null;
	/**
	 */
	private List<Policy> policies = null;
	/**
	 */
	private ArrayAdapter<Policy> arrayAdapter = null;
	static final int EDIT_POLICY = 0;
	static final int NEW_POLICY = 1;
	/**
	 */
	private BroadcastReceiver receiver;

	@Override
	public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        
        // Init Policy Facade
        policyFacade = PolicyFacadeMockImpl.getInstance();
        
        // Set Receiver
        receiver = new BroadcastReceiver() {
        	
        	private PolicyFacadeInterface policyFacade = PolicyFacadeMockImpl.getInstance();
        	
	    	@Override
	   	 	public void onReceive(Context context, Intent intent) {  		 
		   		 Bundle extras = intent.getExtras();
		   		 if (extras != null) {
		   			String state = extras.getString(TelephonyManager.EXTRA_STATE);
		   			if (state.equals(TelephonyManager.EXTRA_STATE_RINGING)) {
		   				String phoneNumber = extras.getString(TelephonyManager.EXTRA_INCOMING_NUMBER);
		   				List<Policy> policies = policyFacade.test(phoneNumber);
		   				for(Policy policy : policies) {
		   					policy.executeCommand(context);
		   				}
		   			}
		   		 }
		   	 	}
		     };
	     registerReceiver(receiver, new IntentFilter("android.intent.action.PHONE_STATE"));

        // Set Content View based on policy_tab layout
        setContentView(R.layout.policy_tab);
        
        // Fill ListView with existing policies
        policies = new Vector<Policy>(policyFacade.getElements());
        arrayAdapter = new ArrayAdapter<Policy>(this, android.R.layout.simple_list_item_1, policies);
        setListAdapter(arrayAdapter); 
        
        // Register the ListView for Context Menu and for the OnItemClick event
        ListView lv = getListView();
        lv.setOnItemClickListener(new OnItemClickListener() {
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {      
        		Intent intent = new Intent(PolicyManagementActivity.this, EditPolicyActivity.class);	
        		Policy selectedPolicy = (Policy) getListAdapter().getItem(position);
        		intent.putExtra("policyId", selectedPolicy.getId());   	
	        	startActivityForResult(intent, EDIT_POLICY);
            }
          });
    	  registerForContextMenu(lv);
    }
	
	@Override
	public void onActivityResult(int requestCode, int resultCode, Intent data) {		
		if ((requestCode==EDIT_POLICY) || requestCode==NEW_POLICY) {
            if (resultCode == RESULT_OK) {
            	policies.clear();
            	policies.addAll(policyFacade.getElements());
            	arrayAdapter.notifyDataSetChanged();
	            Toast.makeText(this, "Policy saved", Toast.LENGTH_SHORT).show();
            }
        }
	}
	
	@Override
	public boolean onCreateOptionsMenu(Menu menu) {		
	    MenuInflater inflater = getMenuInflater();
	    inflater.inflate(R.menu.policy_menu, menu);
	    return true;
	}
	
	@Override
	public boolean onOptionsItemSelected(MenuItem item) {	
	    // Handle item selection
	    switch (item.getItemId()) {
	        case R.id.addPolicy:
	        	Intent intent = new Intent(this, NewPolicyActivity.class);
	        	startActivityForResult(intent, NEW_POLICY);
	            return true;
	        default:
	            return super.onOptionsItemSelected(item);
	    }
	}
	
	@Override
	public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo) {		
	    super.onCreateContextMenu(menu, v, menuInfo);
	    MenuInflater inflater = getMenuInflater();
	    inflater.inflate(R.menu.policy_context_menu, menu);
	}
	
	@Override
	public boolean onContextItemSelected(MenuItem item) {		
	    AdapterContextMenuInfo info = (AdapterContextMenuInfo) item.getMenuInfo();
	    Policy selectedPolicy = (Policy) getListAdapter().getItem(info.position);
	    switch (item.getItemId()) {
	        case R.id.deletePolicy:
	        	AlertDialog alert = createDeletePolicyDialog(selectedPolicy);
	        	alert.show();
	            return true;
	        default:
	            return super.onContextItemSelected(item);
	    }
	}
	
	private AlertDialog createDeletePolicyDialog(final Policy policy) {		
		AlertDialog.Builder builder = new AlertDialog.Builder(this);
		builder.setMessage(R.string.delete_policy_dialog_name)
		       .setCancelable(false)
		       .setPositiveButton("Yes", new DialogInterface.OnClickListener() {
		           public void onClick(DialogInterface dialog, int id) {
		                
		        	   PolicyManagementActivity.this.policyFacade.removeElement(policy.getId());
		        	   PolicyManagementActivity.this.policies.remove(policy);
		        	   PolicyManagementActivity.this.arrayAdapter.notifyDataSetChanged();
		           }
		       })
		       .setNegativeButton("No", new DialogInterface.OnClickListener() {
		           public void onClick(DialogInterface dialog, int id) {
		                
		        	   dialog.cancel();
		           }
		       });
		return builder.create();
	}
}
